package com.example.alternateThread.syn;

public class AlternateThread extends Thread {
    private static final Object lock = new Object();
    private static int i = 0;
    private static int flag = 0;
    private final int num;

    public AlternateThread(int num) {
        this.num = num;
    }
    //打印结果
    //线程0打印：93
    //线程1打印：94
    //线程2打印：95
    //线程0打印：96
    //线程1打印：97
    //线程2打印：98
    //线程0打印：99
//    @Override
//    public void run() {
//        synchronized (lock) {
//            while (i < 100) {
//                if (num == flag) {
//                    System.out.println("线程" + num + "打印：" + i++);
//                    flag = (flag + 1) % 3;
//                    lock.notifyAll();
//                } else {
//                    try {
//                        lock.wait();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
//    }

    //打印结果如下，原因是线程0打印：99后将线程1、线程2唤醒，两者都会分别执行一次打印，然后再进行i<100的判断，发现不符合了终止循环
    //线程0打印：96
    //线程1打印：97
    //线程2打印：98
    //线程0打印：99
    //线程1打印：100
    //线程2打印：101
    @Override
    public void run() {
        while (i < 100) {
            synchronized (lock) {
                while (num != flag) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("线程" + num + "打印：" + i++);
                flag = (flag + 1) % 3;
                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        AlternateThread thread0 = new AlternateThread(0);
        AlternateThread thread1 = new AlternateThread(1);
        AlternateThread thread2 = new AlternateThread(2);
        thread0.start();
        thread1.start();
        thread2.start();
    }
}
